/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.logist;

import dp1.titandevelop.titano.bean.Mensajes;
import dp1.titandevelop.titano.persistent.Proveedor;
import dp1.titandevelop.titano.persistent.RequerimientoXProducto;
import dp1.titandevelop.titano.service.CotizacionService;
import dp1.titandevelop.titano.service.ProveedorService;
import dp1.titandevelop.titano.service.RequerimientoService;
import dp1.titandevelop.titano.service.ValidacionService;
import java.awt.Dimension;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author chrestean
 */
public class ModulosT_LOG_NuevaCotizacion extends javax.swing.JInternalFrame {

    private ArrayList<RequerimientoXProducto> listaDetalleRequerimiento;
    private ArrayList<Float> listaPrecios;
    private AbstractTableModel modelo = new AbstractTableModel() {
        public int getRowCount() {
            return listaDetalleRequerimiento.size();

        }

        public int getColumnCount() {
            return 5;

        }

        public Object getValueAt(int fi, int co) {
            switch (co) {
                case 0:
                    return listaDetalleRequerimiento.get(fi).getToProducto().getIdproducto();
                case 1:
                    return listaDetalleRequerimiento.get(fi).getToProducto().getDescripcion();
                case 2:
                    return listaDetalleRequerimiento.get(fi).getCantidad();
                case 3:
                    return listaDetalleRequerimiento.get(fi).getToProducto().getUm();
                case 4:
                    return listaPrecios.get(fi);


            }
            return null;
        }

        @Override
        public String getColumnName(int co) {
            String[] t = {"Id Producto", "Producto", "Cantidad", "Unidades", "Monto"};
            return t[co];
        }
    };

    public ModulosT_LOG_NuevaCotizacion() {
        initComponents();
        listaDetalleRequerimiento = new ArrayList<RequerimientoXProducto>();
        this.datePkFechaRec.setDate(new Date());
        this.jTable1.setModel(modelo);
        this.listaPrecios = new ArrayList<Float>();
        ValidacionService val = new ValidacionService();
        val.NoEscribe(datePkFechaRec);
    }
//    private Cotizacion cotizacion = null;
//    ModulosT_LOG_NuevaCotizacion(ModulosT_LOG_AdministrarCotizaciones caller, Cotizacion c) {
//        // constructor para una edicion
//        this.cotizacion = c;
//        this.caller = caller;
//    }

    public void agregarALista(RequerimientoXProducto rxp) {
        listaDetalleRequerimiento.add(rxp);

        ProveedorService ps = new ProveedorService();
        Proveedor prov = ps.buscarPorId(null, Integer.parseInt(txtIDProveedor.getText()));
        float prec = 0;
        int prec2 = 0;
        for (int i = 0; i < prov.getProductoProveedorArray().size(); i++) {
            if (prov.getProductoProveedorArray().get(i).getToProducto().getIdproducto() == rxp.getToProducto().getIdproducto()) {
                prec = rxp.getCantidad() * prov.getProductoProveedorArray().get(i).getPrecio();
                prec2 = Math.round(prec);
                break;
            }
        }
        listaPrecios.add(Float.parseFloat(prec2 + ""));

    }

    public void setIdProv(int id, String strProv) {
        this.txtIDProveedor.setText("" + id);
        this.txtStrProveedor.setText(strProv);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        apPaterno = new javax.swing.JLabel();
        fechaNac = new javax.swing.JLabel();
        txtIDProveedor = new javax.swing.JTextField();
        txtStrProveedor = new javax.swing.JTextField();
        datePkFechaRec = new org.jdesktop.swingx.JXDatePicker();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        btnGuardar = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        txtMontoTotal = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtIgv = new javax.swing.JTextField();

        setTitle("Nueva Cotizacion");
        setPreferredSize(new java.awt.Dimension(640, 410));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Datos De Distribuidor", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11))); // NOI18N
        jPanel1.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        apPaterno.setText("Proveedor:");

        fechaNac.setText("Fecha Recepción");

        txtIDProveedor.setEditable(false);
        txtIDProveedor.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N
        txtIDProveedor.setEnabled(false);

        txtStrProveedor.setEnabled(false);
        txtStrProveedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtStrProveedorActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/buscar2.png"))); // NOI18N
        jButton1.setToolTipText("Buscar un proveedor");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText("Descripcion:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(apPaterno))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtIDProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtStrProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addComponent(jButton1)
                .addGap(40, 40, 40)
                .addComponent(fechaNac)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(datePkFechaRec, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(datePkFechaRec, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtIDProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(apPaterno))
                    .addComponent(fechaNac))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtStrProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/grabar.png"))); // NOI18N
        btnGuardar.setToolTipText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
        btnSalir.setToolTipText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Cotización de Productos", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));
        jPanel2.setPreferredSize(new java.awt.Dimension(566, 183));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID Producto", "Producto", "Cantidad", "Monto"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/agregar.png"))); // NOI18N
        jButton3.setToolTipText("Agregar Detalle");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel1.setText("Monto Total");

        txtMontoTotal.setEditable(false);
        txtMontoTotal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtMontoTotalActionPerformed(evt);
            }
        });

        jLabel3.setText("Total IGV");

        txtIgv.setEditable(false);
        txtIgv.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtIgvActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 504, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(5, 5, 5))
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtMontoTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(77, 77, 77)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtIgv, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jButton3)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtMontoTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3)
                        .addComponent(txtIgv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(37, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 604, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnGuardar)
                        .addGap(3, 3, 3)
                        .addComponent(btnSalir)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnGuardar)
                    .addComponent(btnSalir))
                .addContainerGap(33, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtMontoTotalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMontoTotalActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtMontoTotalActionPerformed

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        ModulosT_LOG.menucotiza = new AdministrarCotizaciones();
        this.getParent().add(ModulosT_LOG.menucotiza);

        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize = ModulosT_LOG.menucotiza.getSize();
        ModulosT_LOG.menucotiza.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                (desktopSize.height - jInternalFrameSize.height) / 4);
        ModulosT_LOG.menucotiza.show();
        this.dispose();
    }//GEN-LAST:event_btnSalirActionPerformed

    private void txtStrProveedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtStrProveedorActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtStrProveedorActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        RequerimientoService rs = new RequerimientoService();
        if (rs.buscarActivo() != null) {
            if (!this.txtIDProveedor.getText().equals("")) {
                ModulosT_LOG_SeleccionarDetalleRequerimiento dr = new ModulosT_LOG_SeleccionarDetalleRequerimiento(this, Integer.parseInt(this.txtIDProveedor.getText()));
                this.getParent().add(dr);
                this.listaDetalleRequerimiento = new ArrayList<RequerimientoXProducto>();
                this.listaPrecios = new ArrayList<Float>();

                dr.show();
            } else {
                JOptionPane.showMessageDialog(this, "Especifíque primero un proveedor", "Campo Faltante", JOptionPane.ERROR_MESSAGE);

            }
        } else {
            JOptionPane.showMessageDialog(this, "No hay requerimiento activo/en proceso.", "Aviso!", JOptionPane.WARNING_MESSAGE);

        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        ModulosT_LOG_BuscarProveedor bp = new ModulosT_LOG_BuscarProveedor(this);
        this.getParent().add(bp);
        bp.show();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        // TODO add your handling code here:
        Mensajes m = new Mensajes();
        if (!this.txtIDProveedor.getText().equals("") && this.listaDetalleRequerimiento.size() != 0) {
            try {
                CotizacionService cs = new CotizacionService();

                cs.insertarCotizacion(Integer.parseInt(this.txtIDProveedor.getText()), this.datePkFechaRec.getDate(), Float.parseFloat(this.txtMontoTotal.getText()), this.listaDetalleRequerimiento, this.listaPrecios);
                JOptionPane.showInternalMessageDialog(this.getRootPane(), m.getRegistrado(), "Mensaje", JOptionPane.INFORMATION_MESSAGE);


                ModulosT_LOG.menucotiza = new AdministrarCotizaciones();
                this.getParent().add(ModulosT_LOG.menucotiza);

                Dimension desktopSize = this.getParent().getSize();
                Dimension jInternalFrameSize = ModulosT_LOG.menucotiza.getSize();
                ModulosT_LOG.menucotiza.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                        (desktopSize.height - jInternalFrameSize.height) / 4);
                ModulosT_LOG.menucotiza.show();

                this.dispose();

            } catch (Exception e) {
                JOptionPane.showInternalMessageDialog(this.getRootPane(), m.getError(), "Error", JOptionPane.ERROR_MESSAGE);

            }
        } else {
            JOptionPane.showInternalMessageDialog(this.getRootPane(), m.getCompletarCampos(), "Aviso", JOptionPane.WARNING_MESSAGE);

        }

    }//GEN-LAST:event_btnGuardarActionPerformed

    private void txtIgvActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIgvActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtIgvActionPerformed
    //private float monto;
    public void refrescarTabla() {
        this.modelo.fireTableDataChanged();
        float acum = 0;
        for (int i = 0; i < this.listaPrecios.size(); i++) {
            acum = acum + this.listaPrecios.get(i);
        }
        //System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>val: "+acum);
        //this.monto = acum;
        this.txtMontoTotal.setText("" + new DecimalFormat("#.##").format(acum));
        float igv = (0.18f) * acum;
        //int igv2 = Math.round(Float.parseFloat(igv + ""));
        this.txtIgv.setText("" + new DecimalFormat("#.##").format(igv));
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel apPaterno;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnSalir;
    private org.jdesktop.swingx.JXDatePicker datePkFechaRec;
    private javax.swing.JLabel fechaNac;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField txtIDProveedor;
    private javax.swing.JTextField txtIgv;
    private javax.swing.JTextField txtMontoTotal;
    private javax.swing.JTextField txtStrProveedor;
    // End of variables declaration//GEN-END:variables
}
